package adv9;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author oldliu
 * @since 1.0
 */
public class WeatherServer {
    public static void main(String[] args) {
        ServerSocket st = null;
        //线程池
        ExecutorService es = Executors.newFixedThreadPool(20);
        try {
            //在999端口监听
            st = new ServerSocket(9999);
            System.out.println("聊天服务器启动。。。");
            while (true) {
                //连接建立
                final Socket s = st.accept();
                //submit
                //加入线程池
                es.execute(new TianqiThread(s));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class TianqiThread implements Runnable {
    private Socket s;

    public TianqiThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println(s + "连接上服务器了，准备聊天");
        try {
            //获得线程的输入输出流
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            //包装成字符流
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter pw = new PrintWriter(out, true);//true表示自动刷新

            String shenme = null;
            while (true) {
                //读取一行，是客户端要查询的天气类型
                shenme = br.readLine();
                switch (shenme) {
                    case "qiwen":
                        pw.println("12-4度");
                        break;
                    case "pm2.5":
                        pw.println("77");
                        break;
                    case "shidu":
                        pw.println("67%");
                        break;
                    case "tuichu":
                        return;
                    default:
                        pw.println("unkown");
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                s.close();
                System.out.println(s + "关闭连接");
            } catch (Exception e) {

            }
        }
    }
}
